package br.com.seuimovelnamao.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.Session;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import br.com.seuimovelnamao.hibernate.HibernateUtil;

public class HibernateSessionInterceptor extends HandlerInterceptorAdapter {
	
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		
		HibernateUtil hu = new HibernateUtil();
		request.setAttribute("hibernateSession", hu.getSession());

		return true;
		
	}
	
	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {


		Session session = (Session)request.getAttribute("hibernateSession");
		session.close();
	}

}
